package com.jsle.financial.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.jsle.common.Service;
import com.jsle.financial.domain.DataEntity;
import com.jsle.financial.domain.User;
import com.jsle.financial.excel.ExcelParser;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.DateUtil;
import com.jsle.financial.vo.Page;

@Controller
@RequestMapping(value = "/data")
public class DataController {
    private Log log = LogFactory.getLog(DataController.class);
    @Resource
    private Service baseService;

    @RequestMapping(value = "/publish.do", method = RequestMethod.POST)  
    public ModelAndView publish(HttpServletRequest request,HttpServletResponse response, 
    					  @RequestParam("file") MultipartFile file) {
    	AJAXUtil.setCharacterEncoding(request,response);
	    String json = "{\"success\":\"false\"}";
	    String forwardUrl = "/console/publishSuccess";
		String companyCode = WebUtils.findParameterValue(request, "companyCode");
		System.out.println("----" + companyCode);
		System.out.println("----" + file.getName());
		log.info("上传文件："+file.getOriginalFilename());  
		try {
			if (!file.isEmpty()) {  
				this.copyFile(file.getInputStream(), file.getOriginalFilename());  
			}   
			ExcelParser parser = new ExcelParser();
			parser.parse(file.getInputStream());
			List<DataEntity> list = parser.getResult();
			for (DataEntity dataEntity : list) {
				dataEntity.setCompany(companyCode);
				baseService.save(dataEntity);
			    }
		} catch (Exception e) {
			e.printStackTrace();
			forwardUrl = "/console/publishErr";
		}
//	String[] data = new String[] { "2012-11-08", "2012-11-09", "2012-11-10" };
//	for (int i = 0; i < data.length; i++) {
//	    ExcelParser parser = new ExcelParser();
//	    parser.parse(this.getClass().getClassLoader()
//		    .getResourceAsStream("test_data_" + data[i] + ".xlsx"));
//	    List<DataEntity> list = parser.getResult();
//	    for (DataEntity dataEntity : list) {
//		dataEntity.setCompany(company);
//		baseService.save(dataEntity);
//	    }
//	}
		json = "{\"success\":\"ture\"}";
		
		//AJAXUtil.writerJson(response,json);
		return new ModelAndView(forwardUrl);
    }

    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/query", method=RequestMethod.POST)
    @ResponseBody
    public Object query(
	    @RequestParam(value = "type", required = false) String type,
	    @RequestParam(value = "oneDay", required = false, defaultValue = "true") Boolean oneDay,
	    @RequestParam(value = "itemName", required = false) String itemName,
	    @RequestParam(value = "itemNameLike", required = false) String itemNameLike,
	    @RequestParam(value = "itemNames", required = false) String itemNames,HttpServletRequest request,HttpServletResponse response) {
    User user = (User)request.getSession().getAttribute("user");	
	String company = user.getCompanyCode();
	String[] itemNamesList = null;
	if (StringUtils.hasLength(itemNames)) {
	    itemNamesList = itemNames.split(",");
	}

	Map conditions = new HashMap();
	putParam(conditions, "type", type);
	putParam(conditions, "itemName", itemName);
	putParam(conditions, "itemNames", itemNamesList);
	putParam(conditions, "itemNameLike", itemNameLike);
	System.out.println("type:"+type);
	if (oneDay) {
	    conditions.put("accdateBegin",
		    DateUtil.parse(DateUtil.format(DateUtil.getBefore3Day(new Date()))));
	}

	conditions.put("company", company);
	Page page = baseService.queryByConditions(DataEntity.class, conditions);
	return AJAXUtil.pageResult(page);
    }

    @SuppressWarnings("unchecked")
	private void putParam(Map conditions, String key, Object value) {
		if (value == null) {
		    return;
		}
		
		if (value instanceof String && StringUtils.hasLength((String) value)) {
		    conditions.put(key, value);
		    return;
		}
	
		if (value instanceof String[] && ((String[]) value).length > 0) {
		    conditions.put(key, value);
		    return;
		}
	
		conditions.put(key, value);
    }
    
    /**
	 * 写文件到本地 
	 * @param in
	 * @param fileName
	 * @throws IOException
	 */
	private void copyFile(InputStream in,String fileName) throws IOException{  
		FileOutputStream fs = new FileOutputStream("D:/tomcat-cluster/tomcat-finance/upload/" + fileName);  
		byte[] buffer = new byte[1024 * 1024];  
		int bytesum = 0;  
		int byteread = 0;  
		while ((byteread = in.read(buffer)) != -1) {  
			bytesum += byteread;  
			fs.write(buffer, 0, byteread);  
			fs.flush();  
		}  
		fs.close();  
		in.close();  
	}  

}
